﻿using Evan.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.SessionState;

namespace Evan.WebUI
{
    /// <summary>
    /// 前台Ajax基类
    /// </summary>
    public class BaseAshx : IHttpHandler, IRequiresSessionState
    {

        /// <summary>
        /// 虚方法重写即可
        /// </summary>
        /// <param name="context"></param>
        public virtual void ProcessRequest(HttpContext context)
        {

        }


        /// <summary>
        /// 获取表单对象转为dynamic（验证码错误,直接输出结果{ States = false, Msg = "验证码错误，请输入正确的验证码！", Url = "vcode" }）
        /// </summary>
        /// <param name="context">HttpContext</param>
        /// <param name="skipNameStr">跳过的表单Name,以英文 , 分割</param>
        /// <param name="isVCode">是否检查图形验证码,验证码字段必须命名为:Vcode,By Session("feedback")</param>
        /// <param name="isECode">是否检查邮箱验证码,验证码字段必须命名为:Ecode,By Session("feedback")</param>
        /// <param name="isPass">是否包含密码字段,密码字段必须命名为:UserPwd</param>
        public dynamic ContextFormToDynamic(HttpContext context, string skipNameStr = "", bool isVCode = false, bool isECode = false, bool isPass = false)
        {
            dynamic model = new Evan.Model.DynamicModel();
            var form = context.Request.Form;//获取前台表单对象
            var skipNameArr = new List<string>();

            if (!string.IsNullOrEmpty(skipNameStr))
            {
                skipNameArr = skipNameStr.Split(',').ToList();
            }

            //检查验证码
            if (isVCode)
            {
                skipNameArr.Add("Vcode");
                if (!CheckVCode(form["Vcode"]))
                    JsonResult(context, new Result { States = false, Msg = "验证码错误，请输入正确的验证码！", Url = "vcode" });
                else
                {
                    Evan.Common.CommFun.DelSession("feedback");
                }
            }

            //检查邮箱验证码
            if (isECode)
            {
                skipNameArr.Add("Ecode");
                if (!CheckECode(form["Ecode"]))
                    JsonResult(context, new Result { States = false, Msg = "邮箱验证码错误，请输入正确的验证码！", Url = "vcode" });
                else
                {
                    Evan.Common.CommFun.DelSession("ecode");
                }
            }


            foreach (string item in form)
            {
                if (skipNameArr.Count(x => x.ToLower() == item.ToLower()) > 0) continue;

                if (isPass && item == "UserPwd")
                {
                    model.Set(item, Evan.Common.CommFun.EnPwd(form[item]));//数据对象添加到Model
                }
                else
                {
                    model.Set(item, form[item]);//数据对象添加到Model
                }
            }

            return model;
        }


        /// <summary>
        /// 检查验证码是否正确 By Session("feedback")
        /// </summary>
        /// <param name="vcode">验证码</param>
        protected bool CheckVCode(string vcode)
        {
            bool result = false;
            string sessionCode = CommFun.ReadSession("feedback") as string;

            if (sessionCode != null && string.Equals(vcode, sessionCode, StringComparison.CurrentCultureIgnoreCase))
                result = true;

            return result;
        }

        /// <summary>
        /// 检查邮箱验证码是否正确 By Session("ECode")
        /// </summary>
        /// <param name="ecode">验证码</param>
        protected bool CheckECode(string ecode)
        {
            bool result = false;
            string sessionCode = CommFun.ReadSession("ecode") as string;

            if (sessionCode != null && string.Equals(ecode, sessionCode, StringComparison.CurrentCultureIgnoreCase))
                result = true;

            return result;
        }


        /// <summary>
        /// 输出结果
        /// </summary>
        protected void JsonResult(HttpContext context, dynamic result)
        {
            context.Response.Write(JsonConvert.SerializeObject(result));
            context.Response.End();
        }

        /// <summary>
        /// Ajax返回信息类
        /// </summary>
        public class Result
        {
            public bool States { get; set; }
            public string Msg { get; set; }
            public string Url { get; set; }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}
